#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

static int glob = 0;


static void* thread_func(void* arg)
{
  static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; 
  // pthread_mutex_t mtx;
 
  int loops = *((int*)arg);
  int loc,j,s;

  // s = pthread_mutex_init(&mtx,NULL);
  // if (s!=0) printf("Failed to init a mutex\n");

  for (j = 0; j < loops; j++) {
    s = pthread_mutex_lock(&mtx);
    if (s != 0)
      printf("Failed to lock a mutex\n");
    loc = glob;
    loc++;
    glob = loc;
    
    s = pthread_mutex_unlock(&mtx);
    if (s != 0)
      printf("Failed to unlock a mutex\n");
  }
  
  return NULL;
}

int main(int argc, char *argv[])
{
  pthread_t t1, t2;
  int loops, s;
  loops = (argc > 1)? atoi(argv[1]) : 10000000;
  s = pthread_create(&t1,NULL,thread_func,&loops);
  if (s!=0) printf("Failed to create thread t1\n");
  s = pthread_create(&t2,NULL,thread_func,&loops);
  if (s!=0) printf("Failed to create thread t2\n");
  s = pthread_join(t1,NULL);
  if (s!=0) printf("Failed to join t1\n");
  s = pthread_join(t2,NULL);
  if (s!=0) printf("Failed to join t2\n");

  printf("glob = %d\n", glob);
  exit(EXIT_SUCCESS);
}
